package com.cygsunri.event.websocket.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cygsunri.event.entity.EventInfo;
import com.cygsunri.event.entity.EventParams;
import com.cygsunri.event.service.EventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket服务
 */
@Slf4j
@ServerEndpoint("/ws/processed/event")
@Component
public class WebSocketServer {

    private static EventService eventService;

    @Autowired
    public void setEventService(EventService eventService) {
        WebSocketServer.eventService = eventService;
    }


    /**
     * 解决无法注入
     */
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineNum = new AtomicInteger();

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
     */
    private static Set<Session> sessionPools = new CopyOnWriteArraySet<>();

    private static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    private static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    /**
     * 发送消息
     */
    private static void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 向各个客户端推送事件
     *
     * @param msg 事件的json字符串
     */
    public static void broadcast(String msg) {
        for (Session session : sessionPools) {
            try {
                sendMessage(session, msg);
            } catch (IOException e) {
                sessionPools.remove(session);
                try {
                    session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }
    }

    /**
     * 建立连接成功调用
     */
    @OnOpen
    public void onOpen(Session session) {
        sessionPools.add(session);
        addOnlineCount();

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate today = LocalDate.now();
        LocalDate lastweek = today.plusDays(-3);

        EventParams eventParams = new EventParams();
        eventParams.setEventType("all");
        eventParams.setConfirm("false");
        eventParams.setSearchName("");
        eventParams.setStartDate(lastweek.format(df));
        eventParams.setEndDate(today.format(df));
        List<EventInfo> eventList = eventService.getEventInfoList(eventParams);

        try {
            sendMessage(session, JSON.toJSONString(eventList, SerializerFeature.DisableCircularReferenceDetect));
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("加入webSocket！当前人数为" + onlineNum);
    }

    /**
     * 关闭连接时调用
     */
    @OnClose
    public void onClose(Session session) {
        sessionPools.remove(session);
        subOnlineCount();
        log.info(session + "断开webSocket连接！当前人数为" + onlineNum);
    }

    /**
     * 收到客户端信息
     */
    @OnMessage
    public void onMessage(String message) {
       /* message = "客户端：" + message + ",已收到";
        log.info(message);*/
        EventService eventService = applicationContext.getBean(EventService.class);
        List<EventInfo> infoList = JSON.parseArray(message, EventInfo.class);
        if (infoList != null) {
            eventService.confirmEventList(infoList);
        }
    }

    /**
     * 错误时调用
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("发生错误");
        throwable.printStackTrace();
    }
}
